import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Warehouse, Location, WarehouseWithLocations, DepartmentNode } from '../storehouse.service';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
import { ManagerSelectDialogComponent } from '../manager-select-dialog/manager-select-dialog.component';
import { StorehouseService } from '../storehouse.service';

@Component({
  selector: 'app-storehouse-form',
  templateUrl: './storehouse-form.component.html',
  styleUrls: ['./storehouse-form.component.scss'],
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, ManagerSelectDialogComponent]
})
export class StorehouseFormComponent implements OnInit {
  @Input() visible = false;
  @Input() isEdit = false;
  @Input() set initialData(data: any) {
    console.log('1. Received initial data:', data);
    if (!data) {
      console.log('No data received');
      // 新增：清空表单和库位
      const storehouseForm = this.formGroup.get('storehouse') as FormGroup;
      storehouseForm.reset({
        id: '',
        warehouseCode: '',
        warehouseName: '',
        warehouseCapacity: 0,
        warehouseAddress: '',
        managementDept: '',
        warehouseManager: '',
        phone: '',
        sort: 0,
        warehouseStatus: '启用',
        remarks: ''
      });
      const locationsArray = this.formGroup.get('locations') as FormArray;
      while (locationsArray.length !== 0) {
        locationsArray.removeAt(0);
      }
      this.addLocation();
      return;
    }

    try {
      // 更新仓库基本信息
      const storehouseForm = this.formGroup.get('storehouse') as FormGroup;
      console.log('2. Updating storehouse form with:', data);
      
      // 获取仓库数据，处理不同的数据结构
      const warehouseData = data.storehouse || data;
      console.log('Warehouse data to process:', warehouseData);
      
      // 确保所有必要的字段都存在
      const formData = {
        id: warehouseData.id || '',
        warehouseCode: warehouseData.warehouseCode || '',
        warehouseName: warehouseData.warehouseName || '',
        warehouseCapacity: warehouseData.warehouseCapacity || 0,
        warehouseAddress: warehouseData.warehouseAddress || '',
        managementDept: warehouseData.managementDept || '',
        warehouseManager: warehouseData.warehouseManager || '',
        phone: warehouseData.phone || '',
        sort: warehouseData.sort || 0,
        warehouseStatus: warehouseData.warehouseStatus || '启用',
        remarks: warehouseData.remarks || ''
      };
      
      console.log('Form data to patch:', formData);
      storehouseForm.patchValue(formData);
      console.log('After patching storehouse form:', storehouseForm.value);

      // 获取库位信息数组
      const locationsArray = this.formGroup.get('locations') as FormArray;
      
      // 清空现有的库位
      while (locationsArray.length !== 0) {
        locationsArray.removeAt(0);
      }

      // 获取库位数据，处理不同的数据结构
      const locationData = warehouseData.locations || data.locations || [];
      console.log('3. Location data to process:', locationData);

      // 添加库位数据
      if (locationData.length > 0) {
        locationData.forEach((location: any) => {
          console.log('4. Processing location:', location);
          const locationGroup = this.fb.group({
            locationId: [location.locationId || location.id || '', Validators.required],
            locationName: [location.locationName || location.name || '', Validators.required],
            capacity: [location.capacity || 0],
            supervisor: [location.supervisor || ''],
            status: [location.status || 0],
            sortOrder: [location.sortOrder || location.sort || 0],
            remarks: [location.remarks || '']
          });
          console.log('Created location form group:', locationGroup.value);
          locationsArray.push(locationGroup);
        });
      } else {
        console.log('No locations found, adding empty location');
        this.addLocation();
      }
      
      console.log('5. Final form value:', this.formGroup.value);
    } catch (error) {
      console.error('Error in initialData setter:', error);
    }
  }
  @Output() cancel = new EventEmitter<void>();
  @Output() submit = new EventEmitter<WarehouseWithLocations>();

  defaultCode = false;
  formGroup: FormGroup;
  departmentTree: DepartmentNode[] = [];
  showDepartmentDropdown = false;
  selectedDepartments: DepartmentNode[] = [];
  selectedDepartmentName = '';

  get locationArray() {
    return this.formGroup.get('locations') as FormArray;
  }

  showManagerDialog = false;

  constructor(
    private fb: FormBuilder,
    private storehouseService: StorehouseService
  ) {
    this.formGroup = this.fb.group({
      storehouse: this.fb.group({
        id: [''],
        warehouseCode: ['', Validators.required],
        warehouseName: ['', Validators.required],
        warehouseCapacity: [0, Validators.required],
        warehouseAddress: [''],
        managementDept: [''],
        warehouseManager: [''],
        phone: [''],
        sort: [0],
        warehouseStatus: ['启用'],
        remarks: ['']
      }),
      locations: this.fb.array([])
    });
  }

  ngOnInit() {
    // 加载部门树数据
    this.loadDepartmentTree();

    if (this.isEdit && this.initialData) {
      this.formGroup.patchValue({
        storehouse: {
          warehouseCode: this.initialData.storehouse.warehouseCode,
          warehouseName: this.initialData.storehouse.warehouseName,
          warehouseCapacity: this.initialData.storehouse.warehouseCapacity,
          warehouseAddress: this.initialData.storehouse.warehouseAddress,
          managementDept: this.initialData.storehouse.managementDept,
          warehouseManager: this.initialData.storehouse.warehouseManager,
          phone: this.initialData.storehouse.phone,
          sort: this.initialData.storehouse.sort,
          warehouseStatus: this.initialData.storehouse.warehouseStatus,
          remarks: this.initialData.storehouse.remarks
        }
      });

      // 设置已选择的部门名称
      this.selectedDepartmentName = this.initialData.storehouse.managementDept;

      // 清空并重新添加库位
      this.locationArray.clear();
      if (this.initialData.locations) {
        this.initialData.locations.forEach(location => {
          this.addLocation(location);
        });
      }
    } 
  }

  onDefaultCodeChange() {
    const warehouseCodeControl = this.formGroup.get('storehouse.warehouseCode');
    if (this.defaultCode) {
      const code = this.generateWarehouseCode();
      warehouseCodeControl?.setValue(code);
    } else {
      warehouseCodeControl?.setValue('');
    }
  }

  private generateWarehouseCode(): string {
    const prefix = 'WH';
    const timestamp = new Date().getTime().toString().slice(-6);
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `${prefix}${timestamp}${random}`;
  }

  addLocation(location?: Location) {
    const locationGroup = this.fb.group({
      locationId: [location?.locationId || '', Validators.required],
      locationName: [location?.locationName || '', Validators.required],
      capacity: [location?.capacity || 0],
      supervisor: [location?.supervisor || ''],
      status: [location?.status || 0],
      sortOrder: [location?.sortOrder || 0],
      remarks: [location?.remarks || '']
    });
    this.locationArray.push(locationGroup);
  }

  removeLocation(index: number) {
    this.locationArray.removeAt(index);
  }

  onSubmit() {
    if (this.formGroup.valid) {
      const formValue = this.formGroup.value;
      console.log('Form value before submit:', formValue);
      console.log('Is editing:', this.isEdit);

      const submitData: WarehouseWithLocations = {
        id: this.isEdit ? this.initialData?.storehouse?.id || '' : '',
        storehouse: {
          ...formValue.storehouse,
          // 如果是编辑模式，确保包含 id
          id: this.isEdit ? formValue.storehouse.id : undefined,
          warehouseCapacity: Number(formValue.storehouse.warehouseCapacity) || 0,
          sort: formValue.storehouse.sort?.toString() || '0',
          warehouseStatus: formValue.storehouse.warehouseStatus || '启用',
          remarks: formValue.storehouse.remarks || ''
        },
        locations: formValue.locations.map((location: any) => ({
          locationId: location.locationId,
          locationName: location.locationName,
          capacity: Number(location.capacity) || 0,
          supervisor: location.supervisor || '',
          status: Number(location.status) || 0,
          sortOrder: Number(location.sortOrder) || 0,
          remarks: location.remarks || ''
        }))
      };

      console.log('Submit data:', submitData);
      this.submit.emit(submitData);
      
      // 重置表单
      if (!this.isEdit) {
        this.formGroup.reset({
          storehouse: {
            id: '',
            warehouseCode: '',
            warehouseName: '',
            warehouseCapacity: 0,
            warehouseAddress: '',
            managementDept: '',
            warehouseManager: '',
            phone: '',
            sort: 0,
            warehouseStatus: '启用',
            remarks: ''
          },
          locations: []
        });
        this.defaultCode = false;
        // 添加一个空的库位
        this.addLocation();
      }
    }
  }

  onCancel() {
    this.cancel.emit();
  }

  showManagerSelect() {
    this.showManagerDialog = true;
  }

  onManagerSelectCancel() {
    this.showManagerDialog = false;
  }

  onManagerSelectConfirm(manager: string) {
    this.formGroup.get('storehouse.warehouseManager')?.setValue(manager);
    this.showManagerDialog = false;
  }

  // 加载部门树数据
  loadDepartmentTree() {
    this.storehouseService.getDepartmentTree().subscribe(
      data => {
        this.departmentTree = data;
      },
      error => {
        console.error('Failed to load department tree:', error);
      }
    );
  }

  // 切换部门下拉框显示状态
  toggleDepartmentDropdown() {
    this.showDepartmentDropdown = !this.showDepartmentDropdown;
  }

  // 选择部门
  selectDepartment(dept: DepartmentNode, level: number) {
    // 更新选中的部门数组
    this.selectedDepartments = this.selectedDepartments.slice(0, level);
    this.selectedDepartments[level] = dept;

    // 如果选择了最后一级，或者当前选中的部门没有子部门
    if (level === 2 || !dept.children?.length) {
      // 构建完整的部门路径名称
      this.selectedDepartmentName = this.selectedDepartments
        .map(d => d.name)
        .filter(name => name)
        .join(' / ');

      // 更新表单值
      this.formGroup.patchValue({
        storehouse: {
          managementDept: this.selectedDepartmentName
        }
      });

      // 关闭下拉框
      this.showDepartmentDropdown = false;
    }

    // 如果不是最后一级且有子部门，加载子部门数据
    if (level < 2 && !dept.children?.length) {
      this.storehouseService.getDepartmentChildren(dept.id).subscribe(
        children => {
          const updatedDept = { ...dept, children };
          if (level === 0) {
            this.departmentTree = this.departmentTree.map(d => 
              d.id === dept.id ? updatedDept : d
            );
          } else {
            const parentDept = this.selectedDepartments[level - 1];
            if (parentDept && parentDept.children) {
              parentDept.children = parentDept.children.map(d =>
                d.id === dept.id ? updatedDept : d
              );
            }
          }
        },
        error => {
          console.error('Failed to load department children:', error);
        }
      );
    }
  }
}

styles: [`
  .form-dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }

  .form-dialog {
    background: white;
    border-radius: 8px;
    width: 80%;
    max-width: 1200px;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    animation: dialog-fade-in 0.3s ease;
  }

  @keyframes dialog-fade-in {
    from {
      opacity: 0;
      transform: translateY(-20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .form-dialog-header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .form-dialog-header h2 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }

  .close-button {
    background: none;
    border: none;
    font-size: 20px;
    color: #999;
    cursor: pointer;
    padding: 0;
    line-height: 1;
  }

  .form-dialog-body {
    padding: 24px;
    overflow-y: auto;
    flex: 1;
  }

  /* 仓库状态标签样式 */
  :host ::ng-deep .warehouse-status {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
  }

  :host ::ng-deep .warehouse-status.locked {
    background-color: #FFA940;  /* 橙色背景 */
    color: #873800;  /* 深橙色文字 */
  }

  :host ::ng-deep .warehouse-status.enabled {
    background-color: #95DE64;  /* 绿色背景 */
    color: #135200;  /* 深绿色文字 */
  }

  :host ::ng-deep .warehouse-status.disabled {
    background-color: #FF7875;  /* 红色背景 */
    color: #5C0011;  /* 深红色文字 */
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #262626;
    margin-bottom: 16px;
    padding-left: 12px;
    border-left: 4px solid #409eff;
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 24px;
  }

  .form-item {
    display: flex;
    flex-direction: column;
  }

  .form-item.full-width {
    grid-column: span 3;
  }

  .form-item label {
    margin-bottom: 8px;
    color: #606266;
    font-size: 14px;
  }

  .form-item input,
  .form-item select,
  .form-item textarea {
    height: 36px;
    padding: 0 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;
    font-size: 14px;
  }

  .form-item textarea {
    height: 80px;
    padding: 8px 12px;
    resize: vertical;
  }

  .form-item input:focus,
  .form-item select:focus,
  .form-item textarea:focus {
    border-color: #409eff;
    outline: none;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  .required {
    color: #f56c6c;
    margin-right: 4px;
  }

  .error-message {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
  }

  .locations-container {
    margin-top: 16px;
  }

  .locations-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 16px;
  }

  .locations-table th,
  .locations-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #ebeef5;
    font-size: 14px;
  }

  .locations-table th {
    background-color: #fafafa;
    color: #606266;
    font-weight: 500;
  }

  .locations-table td input,
  .locations-table td select {
    width: 100%;
    height: 32px;
    padding: 0 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 14px;
  }

  .btn-delete {
    padding: 6px;
    background: none;
    border: none;
    color: #f56c6c;
    cursor: pointer;
    transition: all 0.3s;
  }

  .btn-delete:hover {
    color: #ff7875;
  }

  .btn-lock {
    padding: 6px;
    background: none;
    border: none;
    color: #E6A23C;
    cursor: pointer;
    transition: all 0.3s;
  }

  .btn-lock:hover {
    color: #F3B760;
  }

  .btn-lock.locked {
    color: #67C23A;
  }

  .btn-lock.locked:hover {
    color: #85CE61;
  }

  .add-location {
    margin-top: 16px;
  }

  .add-location button {
    padding: 8px 16px;
    background: none;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    color: #595959;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;
  }

  .add-location button:hover {
    border-color: #40a9ff;
    color: #40a9ff;
  }

  .form-dialog-footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  .btn-cancel,
  .btn-submit {
    padding: 8px 20px;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
  }

  .btn-cancel {
    border: 1px solid #d9d9d9;
    background: white;
    color: #595959;
  }

  .btn-cancel:hover {
    color: #40a9ff;
    border-color: #40a9ff;
  }

  .btn-submit {
    border: none;
    background: #409eff;
    color: white;
  }

  .btn-submit:hover {
    background: #66b1ff;
  }

  .input-group {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .input-group input {
    flex: 1;
  }

  .checkbox-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 8px;
  }

  .checkbox-wrapper input[type="checkbox"] {
    width: 16px;
    height: 16px;
    margin: 0;
  }

  .checkbox-wrapper label {
    margin: 0;
    font-size: 14px;
    color: #606266;
    cursor: pointer;
  }

  /* 级联选择器样式 */
  .cascader-container {
    position: relative;
    width: 100%;
  }

  .cascader-input {
    position: relative;
    width: 100%;
    cursor: pointer;
  }

  .cascader-input input {
    width: 100%;
    padding-right: 24px;
    cursor: pointer;
    background-color: #fff;
  }

  .cascader-arrow {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    transition: transform 0.3s;
    font-size: 12px;
    color: #909399;
  }

  .cascader-arrow.open {
    transform: translateY(-50%) rotate(180deg);
  }

  .cascader-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    display: flex;
    background: white;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    margin-top: 5px;
  }

  .cascader-menu {
    min-width: 160px;
    height: 200px;
    overflow-y: auto;
    border-right: 1px solid #dcdfe6;
  }

  .cascader-menu:last-child {
    border-right: none;
  }

  .cascader-item {
    padding: 8px 12px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    color: #606266;
  }

  .cascader-item:hover {
    background-color: #f5f7fa;
  }

  .cascader-item.active {
    color: #409eff;
    font-weight: bold;
    background-color: #ecf5ff;
  }

  .cascader-item .arrow {
    font-size: 12px;
    color: #909399;
  }

  /* 滚动条样式 */
  .cascader-menu::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .cascader-menu::-webkit-scrollbar-thumb {
    border-radius: 3px;
    background: #c0c4cc;
  }

  .cascader-menu::-webkit-scrollbar-track {
    border-radius: 3px;
    background: #f5f7fa;
  }
`] 